package com.ciwong.epaper.ui;

import android.content.Context;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.epaper.bean.SchoolDetails;
import com.ciwong.epaper.modules.epaper.bean.SchoolPageBean;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.utils.Utils;
import com.ciwong.epaper.widget.wheel.adapter.SearchSchoolAdapter;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.ciwong.mobilelib.widget.listview.PullRefreshController;
import com.ciwong.mobilelib.widget.listview.PullRefreshListView;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * @description:实名登录搜索学校页面
 * @author: wyk
 * @time: 2021/8/12 11:26
 */
public class SearchSchoolActivity extends BaseActivity implements PullRefreshController.PullRefreshListener, View.OnClickListener {

    private ImageView choose_school_go_back;

    private LinearLayout search_school_layout;

    private EditText edt_searching_book_str;

    private ImageView iv_clear_keywords;

    private PullRefreshListView search_city_lv;

    private SearchSchoolAdapter searchSchoolAdapter;

    /**
     * 获取到的学校集合
     */
    private List<SchoolDetails> mSchoolDetails = new ArrayList<>();

    /**
     * 地区名
     */
    private String mAreaStr;

    /**
     * mSchoolArea :地区码
     * mKeyWords:搜索关键字
     */
    private String mSchoolArea, mKeyWords,brandId;

    private int mPageIndex = 1;
    private int mPageSize = 50;


    @Override
    protected int setView() {
        return R.layout.activity_search_school;
    }

    @Override
    protected void findViews() {
        choose_school_go_back = findViewById(R.id.choose_school_go_back);
        search_school_layout = findViewById(R.id.search_school_layout);
        edt_searching_book_str = findViewById(R.id.edt_searching_book_str);
        iv_clear_keywords = findViewById(R.id.iv_clear_keywords);
        search_city_lv = findViewById(R.id.search_city_lv);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_clear_keywords) {
            String text = edt_searching_book_str.getText().toString().trim();
            /*if (TextUtils.isEmpty(text)) {
             CWToast.makeText(this, "搜索关键字不能为空", Toast.LENGTH_SHORT, true).setToastType(CWToast.TOAST_TYPE_ERROR).show();
                return;
            }*/
            mKeyWords = text;
            try {
                mKeyWords = java.net.URLEncoder.encode(mKeyWords, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                mKeyWords = "";
            }
            //mKeyWords = text;
            mPageIndex = 1;
            showCricleProgress();
            getSchoolList("", "", mKeyWords,text);
        } else if (id == R.id.choose_school_go_back) {
            finish();
        }
    }

    @Override
    protected void initEvent() {
        //监听edit确认按钮
        edt_searching_book_str.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //Toast.LENGTH_LONG表示显示时间长  Toast.LENGTH_SHORT表示显示时间短
                String text = edt_searching_book_str.getText().toString().trim();
                /*if (TextUtils.isEmpty(text)) {
                CWToast.makeText(this, "搜索关键字不能为空", Toast.LENGTH_SHORT, true).setToastType(CWToast.TOAST_TYPE_ERROR).show();
                    return true;
                }*/
                mKeyWords = text;
                try {
                    mKeyWords = java.net.URLEncoder.encode(mKeyWords, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    mKeyWords = "";
                }
                // mKeyWords = text;
                showCricleProgress();
                mPageIndex = 1;
                getSchoolList("", "", mKeyWords,text);

                //隐藏软键盘
                InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(
                        Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                }
                return true;
            }
        });

        iv_clear_keywords.setOnClickListener(this);
        search_city_lv.setPullRefreshEnable(false);
        search_city_lv.setPullRefreshListener(this);
        search_city_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                SchoolDetails schoolDetails = (SchoolDetails) adapterView.getItemAtPosition(i);
                CWSys.setSharedString(BaseConstants.SHARE_KEY_SCHOOL_AREA, mSchoolArea);
                CWSys.setSharedString(BaseConstants.SHARE_KEY_AREA_STR, mAreaStr);
                returnSchool(schoolDetails);

            }
        });
        choose_school_go_back.setOnClickListener(this);

    }

    @Override
    protected void init() {
        //隐藏标题栏
        hideTitleBar();
        Intent intent = getIntent();
        mSchoolArea = intent.getStringExtra(IntentFlag.INTENT_FLAG_SCHOOL_AREA);
        mAreaStr = intent.getStringExtra(IntentFlag.INTENT_FLAG_AREASTR);
        brandId = EApplication.BRAND_ID + "";
        searchSchoolAdapter = new SearchSchoolAdapter(SearchSchoolActivity.this, mSchoolDetails,mKeyWords);
        search_city_lv.setAdapter(searchSchoolAdapter);
    }

    @Override
    protected void loadData() {
        /*mPageIndex = 1;
        showCricleProgress();
        getSchoolList(mSchoolArea, null, mKeyWords);*/
    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onLoadMore() {
        mPageIndex++;
        showCricleProgress();
        String text = edt_searching_book_str.getText().toString().trim();
        mKeyWords = text;
        try {
            mKeyWords = java.net.URLEncoder.encode(mKeyWords, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            mKeyWords = "";
        }
        // CWToast.makeText(this, "搜索关键字不能为空", Toast.LENGTH_SHORT, true).setToastType(CWToast.TOAST_TYPE_ERROR).show();
        getSchoolList(mSchoolArea, null, mKeyWords,text);
    }

    /**
     * 搜索时获取学校所在城市
     */
    private void setCity() {
        for (int i = 0; i < mSchoolDetails.size(); i++) {
            String address = Utils.getAddress(this, mSchoolDetails.get(i).getSchoolArea(), "-");
            mSchoolDetails.get(i).setZoneStr(address);
        }
    }

    /**
     * 查找学校列表 不需要登录
     *
     * @param schoolArea 地区码
     * @param period     学校学段
     * @param keyWords   搜索关键字
     */
    public void getSchoolList(String schoolArea, String period, final String keyWords,final String beforKewWords) {
        EpaperDao.getInstance().getSchoolList(null, period, keyWords, brandId, mPageIndex, mPageSize, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                //super.failed(errorCode,data);
                hideCricleProgress();
                search_city_lv.stopLoadMore();
            }

            @Override
            public void failed(Object data) {
                //super.failed(data);
                hideCricleProgress();
                search_city_lv.stopLoadMore();
            }

            @Override
            public void success(Object data) {
                super.success(data);
                hideCricleProgress();
                if (null != data) {
                    SchoolPageBean schoolPageBean = (SchoolPageBean) data;
                    if (mPageIndex == 1) {
                        if (null != schoolPageBean.getPageList()) {
                            mSchoolDetails = schoolPageBean.getPageList();
                            search_city_lv.setPullLoadEnable(true);
                            //设置学校所在城市
                            //setCity();
                            searchSchoolAdapter.setData(mSchoolDetails,beforKewWords);
                        }
                    } else {
                        if (null != schoolPageBean.getPageList() && schoolPageBean.getPageList().size() > 0) {
                            search_city_lv.stopLoadMore();
                            mSchoolDetails.addAll(schoolPageBean.getPageList());
                            //设置学校所在城市
                            //setCity();
                            searchSchoolAdapter.setData(mSchoolDetails,beforKewWords);

                        } else {
                            search_city_lv.stopLoadMore(true);
                        }
                    }
                }
            }
        });
    }

    /**
     * 返回选择的学校信息
     * @param schoolDetails
     */
    public void returnSchool(SchoolDetails schoolDetails) {
        Intent intent = new Intent();
        intent.putExtra(IntentFlag.INTENT_FLAG_SCHOOL_DATA, schoolDetails);
        setResult(RESULT_OK, intent);
        finish();
    }


}
